package com.example.woke;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.mrwujay.cascade.model.CityModel;
import com.mrwujay.cascade.model.DistrictModel;
import com.mrwujay.cascade.model.ProvinceModel;
import com.mrwujay.cascade.service.XmlParserHandler;
import com.woke.addressactivity.BaseActivity;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

public class DddressmoreActivity extends BaseActivity implements OnClickListener, OnWheelChangedListener {

	private EditText mEname,mEphone,mEtityinfo,mEyoubian;
	private TextView mTcity,mTok,mTcanle,mTsure;
	private View mLinear;
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	public static final String ENCODING = "UTF-8";
	private MyApp application;
	private View mBar;
	private Intentnet net;
	private Intent intent;
	private int intExtra;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dddressmore);
		
		application = (MyApp) getApplication();
		intview();
		
	}

	private void intview() {
		net = new Intentnet();
		intent = getIntent();
		intExtra = intent.getIntExtra("moren", 0);
		findViewById(R.id.adressmore_image_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		mLinear = findViewById(R.id.addressmore_liner_adress);
		mEname = (EditText) findViewById(R.id.ddressmore_edit_name);
		mEphone = (EditText) findViewById(R.id.addressmore_edit_phone);
		mEtityinfo = (EditText) findViewById(R.id.addressmore_edit_cityinfo);
		mEyoubian = (EditText) findViewById(R.id.addressmore_edit_youbian);
		mTcity = (TextView) findViewById(R.id.addressmore_text_city);
		mTok = (TextView) findViewById(R.id.addressmore_text_ok);
		mTcity.setOnClickListener(this);
		mTok.setOnClickListener(this);
		mBar = findViewById(R.id.dddremore_progress_bar);
		mViewProvince = (WheelView) findViewById(R.id.id_province1);
		mViewCity = (WheelView) findViewById(R.id.id_city1);
		mViewDistrict = (WheelView) findViewById(R.id.id_district1);
		mTcanle = (TextView) findViewById(R.id.avuser_info_dressc1);
		mTsure = (TextView) findViewById(R.id.avuser_info_dresssur1);
		mTcanle.setOnClickListener(this);
		mTsure.setOnClickListener(this);
		// ���change�¼�
    	mViewProvince.addChangingListener(this);
    	// ���change�¼�
    	mViewCity.addChangingListener(this);
    	// ���change�¼�
    	mViewDistrict.addChangingListener(this);
    	setUpData();
	}

	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(DddressmoreActivity.this, mProvinceDatas));
		// ���ÿɼ���Ŀ����
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		mViewDistrict.setVisibleItems(7);
		updateCities();
		updateAreas();
	}
	
	/**
	 * ��ݵ�ǰ���У�������WheelView����Ϣ
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		mViewDistrict.setCurrentItem(0);
	}
	
	// ��assets �ļ����л�ȡ�ļ�����ȡ���
			public String getFromAssets(String fileName) {
				String result = "";
				try {
					InputStream in = getResources().getAssets().open(fileName);
					// ��ȡ�ļ����ֽ���
					int lenght = in.available();
					// ����byte����
					byte[] buffer = new byte[lenght];
					// ���ļ��е���ݶ���byte������
					in.read(buffer);
					result = EncodingUtils.getString(buffer, ENCODING);
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return result;
			}

	
	/**
	 * ��ݵ�ǰ��ʡ��������WheelView����Ϣ
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}
	
	/**
	 * ����ʡ�����XML���
	 */
	
    protected void initProvinceDatas()
	{
		List<ProvinceModel> provinceList = null;
    	AssetManager asset = getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // ����һ������xml�Ĺ�������
			SAXParserFactory spf = SAXParserFactory.newInstance();
			// ����xml
			SAXParser parser = spf.newSAXParser();
			XmlParserHandler handler = new XmlParserHandler();
			parser.parse(input, handler);
			input.close();
			// ��ȡ�������������
			provinceList = handler.getDataList();
			//*/ ��ʼ��Ĭ��ѡ�е�ʡ���С���
			if (provinceList!= null && !provinceList.isEmpty()) {
				mCurrentProviceName = provinceList.get(0).getName();
				List<CityModel> cityList = provinceList.get(0).getCityList();
				if (cityList!= null && !cityList.isEmpty()) {
					mCurrentCityName = cityList.get(0).getName();
					List<DistrictModel> districtList = cityList.get(0).getDistrictList();
					mCurrentDistrictName = districtList.get(0).getName();
					mCurrentZipCode = districtList.get(0).getZipcode();
				}
			}
			//*/
			mProvinceDatas = new String[provinceList.size()];
        	for (int i=0; i< provinceList.size(); i++) {
        		// ��������ʡ�����
        		mProvinceDatas[i] = provinceList.get(i).getName();
        		List<CityModel> cityList = provinceList.get(i).getCityList();
        		String[] cityNames = new String[cityList.size()];
        		for (int j=0; j< cityList.size(); j++) {
        			// ����ʡ����������е����
        			cityNames[j] = cityList.get(j).getName();
        			List<DistrictModel> districtList = cityList.get(j).getDistrictList();
        			String[] distrinctNameArray = new String[districtList.size()];
        			DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
        			for (int k=0; k<districtList.size(); k++) {
        				// ����������������/�ص����
        				DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
        				// ��/�ض��ڵ��ʱ࣬���浽mZipcodeDatasMap
        				mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
        				distrinctArray[k] = districtModel;
        				distrinctNameArray[k] = districtModel.getName();
        			}
        			// ��-��/�ص���ݣ����浽mDistrictDatasMap
        			mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
        		}
        		// ʡ-�е���ݣ����浽mCitisDatasMap
        		mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
        	}
        } catch (Throwable e) {  
            e.printStackTrace();  
        } finally {
        	
        } 
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.addressmore_text_city:
			mLinear.setVisibility(View.VISIBLE);
			break;
			
		case R.id.addressmore_text_ok:
//			mEname,mEphone,mEtityinfo,mEyoubian
			String name = ""+mEname.getText().toString().trim();
			String phone = ""+mEphone.getText().toString().trim();
			String cityifo = ""+mEtityinfo.getText().toString().trim();
			String youbian = ""+mEyoubian.getText().toString().trim();
			String trim = mTcity.getText().toString().trim();
			if(name.equals("")){
				Toast.makeText(DddressmoreActivity.this, "请输入名字", Toast.LENGTH_SHORT).show();
			}else if(phone.equals("")){
				Toast.makeText(DddressmoreActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
			}else if(net.isMobile(phone) == false){
				Toast.makeText(DddressmoreActivity.this, "请输入正确手机号", Toast.LENGTH_SHORT).show();
			}else if(cityifo.equals("")){
				Toast.makeText(DddressmoreActivity.this, "请输入详细地址", Toast.LENGTH_SHORT).show();
			}else if(trim.equals("")){
				Toast.makeText(DddressmoreActivity.this, "请选择省市区", Toast.LENGTH_SHORT).show();
			}else{
				sendcityifno(name,phone,cityifo,youbian,trim);
			}
			break;
			
		case R.id.avuser_info_dressc1:
			mLinear.setVisibility(View.GONE);
			break;
			
		case R.id.avuser_info_dresssur1:
			mTcity.setText(mCurrentProviceName+mCurrentCityName);
			mLinear.setVisibility(View.GONE);
			break;

		default:
			break;
		}
	}

	private void sendcityifno(String name, String phone, String cityifo, String youbian, String trim) {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(DddressmoreActivity.this);    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "user");
		params.put("a", "addAddress");
		params.put("userid", application.getDatas_load().getId());
		params.put("phone", phone);
		params.put("name", name);
		params.put("address", trim+cityifo);
		if(youbian.equals("")){
			params.put("code", "000000");
		}else{
			params.put("code", youbian);
		}
		params.put("is_defalut", intExtra);
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						String string = response.getString("info");
						Toast.makeText(DddressmoreActivity.this, ""+string, Toast.LENGTH_SHORT).show();
						setResult(113);
						finish();
					}else{
						Toast.makeText(DddressmoreActivity.this, "保存失败！", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Toast.makeText(DddressmoreActivity.this, "退出失败！", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onFinish() {
				super.onFinish();
				mBar.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		// TODO Auto-generated method stub
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		}else if (wheel == mViewDistrict) {
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
		}
	}
}
